<template>
  <div>
    <en-table-layout :tableData="tableData.data" :loading="loading"  @selection-change="selectedBox" >
      <div slot="toolbar" class="inner-toolbar">
        <div class="toolbar-btns">
          <div>
            <el-button size="mini" type="primary" @click="handleAddShetuan('')">新增</el-button>
            <el-button size="mini" type="primary" @click="copyActivityFn">复制</el-button>
            <el-button size="mini" type="primary" @click="pushNoticeFn">推送提醒</el-button>
          </div>
          <div class="self_flex">
            <el-input placeholder="请输入内容" v-model="shetuanStatus" class="input-with-select">
              <el-select v-model="slectVal" slot="prepend" placeholder="参团状态">
                <el-option label="待审核" value="1"></el-option>
                <el-option label="待上线" value="2"></el-option>
                <el-option label="已上线" value="3"></el-option>
                <el-option label="已下线" value="4"></el-option>
                <el-option label="已驳回" value="5"></el-option>
              </el-select>
              <el-button slot="append" icon="el-icon-search"></el-button>
            </el-input>
            <!-- <el-button type="primary" @click="">高级搜索</el-button> -->
          </div>
        </div>
      </div>

      <template slot="table-columns">
        <el-table-column type="selection" min-width="10" />
        <el-table-column prop="shetuan_no" label="活动编码" min-width="110"/>
        <el-table-column prop="shetuan_name" label="活动名称" min-width="100"/>
        <el-table-column prop="page_popup" label="首页弹窗" min-width="55">
          <template slot-scope="scope">
            <div v-if="scope.row.page_popup === 1">弹窗提醒</div>
            <div v-if="scope.row.page_popup === 0">不弹窗</div>
          </template>
        </el-table-column>
        <el-table-column prop="subscribers_num" label="订阅人数" min-width="55"/>
        <el-table-column  label="活动状态" min-width="100">
          <template slot-scope="scope">
            <div v-if="scope.row.status === 10">待上线</div>
            <div v-if="scope.row.status === 20">报名中</div>
            <div v-if="scope.row.status === 30">已下线</div>
            <div v-if="scope.row.status === 40">已上线</div>
            <div v-if="scope.row.status === 0">已删除</div>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="活动描述" min-width="100"/>
        <!-- <el-table-column prop="shetuan_name" label="活动区域" min-width="100"/> -->
        <el-table-column prop="start_time" label="开售时间" min-width="100">
          <template slot-scope="scope">{{ scope.row.start_time | unixToDate }}</template>
        </el-table-column>
        <el-table-column prop="end_time" label="结束时间" min-width="100">
          <template slot-scope="scope">{{ scope.row.end_time | unixToDate }}</template>
        </el-table-column>
        <el-table-column prop="pick_time" label="提货时间" min-width="100">
          <template slot-scope="scope">{{ scope.row.pick_time | unixToDate }}</template>
        </el-table-column>
        <el-table-column prop="join_stop_time" label="报名截止时间" min-width="100">
          <template slot-scope="scope">{{ scope.row.join_stop_time | unixToDate }}</template>
        </el-table-column>
        <!-- <el-table-column prop="plan_on_time" label="上线时间时间" min-width="100">
          <template slot-scope="scope">{{ scope.row.plan_on_time | unixToDate }}</template>
        </el-table-column> -->
        <el-table-column prop="create_time" label="创建时间" min-width="100">
          <template slot-scope="scope">{{ scope.row.create_time | unixToDate }}</template>
        </el-table-column>
        <!-- <el-table-column prop="" label="创建人" min-width="100"/> -->
        <!-- <el-table-column prop="" label="修改时间" min-width="100"/> -->
        <!-- <el-table-column prop="shetuan_name" label="修改人" min-width="100"/> -->
        <el-table-column  label="参团商品" width="100" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="manageGoods(scope.row.shetuan_id)">商品管理</el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" fixed="right">
          <template slot-scope="scope">
            <el-button v-if="scope.row.status == 30 || scope.row.status == 10" size="mini" type="primary"
              @click="onlineHandle(scope.$index,scope.row.shetuan_id)">上线</el-button>
            <el-button v-if="scope.row.status == 40" size="mini" type="danger"
              @click="offlineHandle(scope.$index,scope.row.shetuan_id)">下线</el-button>
            <el-button size="mini" type="primary"
              @click="handleAddShetuan(scope.row)">修改</el-button>
            <el-button size="mini" type="danger" v-if="scope.row.status === 10"
              @click="handleDeleteShetuan(scope.row.shetuan_id)">删除</el-button>
          </template>
        </el-table-column>
      </template>

      <el-pagination v-if="tableData" slot="pagination"
        @size-change="handlePageSizeChange" @current-change="handlePageCurrentChange"
        :current-page="tableData.page_no" :page-sizes="[10, 20, 50, 100]" :page-size="tableData.page_size"
        layout="total, sizes, prev, pager, next, jumper" :total="tableData.data_total">
      </el-pagination>
    </en-table-layout>

    <!--活动推送 dialog-->
    <el-dialog :title="titleMap[titleType]" :close-on-press-escape="false"
      :visible.sync="dialogPushVisible" width="750px" :close-on-click-modal="false" >
      <el-form :model="pushForm" :rules="pushRules" ref="pushForm" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="8">
              <img src="../../../static/img/preview.png" class="preview" />
          </el-col>
          <el-col :span="16">
            <el-form-item label="活动名称" prop="activity_name">
              <el-input v-model="pushForm.activity_name" :maxlength="20"></el-input>
            </el-form-item>
            <el-form-item label="活动内容" prop="activity_content" v-if="titleType=='push'">
            <el-input type="textarea"  placeholder="最多200个字符"  rows="5" :maxlength="200"
                v-model="pushForm.activity_content"></el-input>
            </el-form-item>
            <el-form-item label="活动时间" prop="activity_time">
              <el-date-picker v-model="pushForm.activity_time" type="datetime"
                placeholder="活动时间" :default-time="mixintime" :picker-options="{disabledDate(time) { return time.getTime() < Date.now() - 8.64E7 }}">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="温馨提示" prop="reminder">
              <el-input v-model="pushForm.reminder" :maxlength="20"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogPushVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitpushForm('pushForm')" :loading="btnLoading">确认推送</el-button>
      </div>
    </el-dialog>

    <!--添加/编辑团购 dialog-->
    <el-dialog :title="titleMap[titleType]" :close-on-press-escape="false"
      :visible.sync="dialogShetuanVisible" width="750px" :close-on-click-modal="false" >
      <el-form :model="shetuanForm" :rules="shetuanRules" ref="shetuanForm" label-width="120px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="活动名称" prop="shetuan_name">
              <el-input v-model="shetuanForm.shetuan_name" placeholder="活动名称" :maxlength="20"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="活动时间段" prop="time_range">
              <el-date-picker v-model="shetuanForm.time_range"
                type="datetimerange" range-separator="-" start-placeholder="开始时间"
                end-placeholder="结束时间" :editable="false" value-format="timestamp"
                :default-time="['00:00:00', '22:59:59']"
                :picker-options="{disabledDate(time) { return time.getTime() < Date.now() - 8.64E7 }}">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="提货时间" prop="pick_time">
              <el-date-picker v-model="shetuanForm.pick_time" type="datetime" :editable="false"
                value-format="timestamp" placeholder="提货时间" :default-time="MixinDefaultTime"
                :picker-options="{disabledDate(time) { return time.getTime() < Date.now() - 8.64E7 }}">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="报名截止时间" prop="join_stop_time">
              <el-date-picker v-model="shetuanForm.join_stop_time" type="datetime" :editable="false"
                value-format="timestamp" placeholder="报名截止时间" :default-time="MixinDefaultTime"
                :picker-options="{disabledDate(time) { return time.getTime() < Date.now() - 8.64E7 }}">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-row>
          <el-col :span="24">
            <el-form-item label="所在地区" prop="region">
              <div class="areaItem">
                <en-region-picker
                  :api="MixinRegionApi"
                  :default="areas"
                  @changed="(object) => { shetuanForm.region = object.last_id }"
                  clearable>
                </en-region-picker>
              </div>
            </el-form-item>
          </el-col>
        </el-row> -->
        <el-row>
          <el-col>
            <el-form-item label="首页弹框" prop="page_popup">
              <el-radio-group v-model="shetuanForm.page_popup">
                <el-radio :label="0">不弹窗</el-radio>
                <el-radio :label="1">弹窗提醒</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-form-item label="上线时间" prop="planOnTime">
          <el-date-picker v-model="shetuanForm.planOnTime" type="datetime" :editable="false"
            value-format="timestamp" placeholder="上线时间" :default-time="MixinDefaultTime"
            :picker-options="{disabledDate(time) { return time.getTime() < Date.now() - 8.64E7 }}">
          </el-date-picker>
        </el-form-item> -->
        <el-form-item label="活动描述" prop="description">
          <el-input type="textarea" placeholder="最多200个字符"  rows="5" :maxlength="200"
            v-model="shetuanForm.description"></el-input>
        </el-form-item>
        <!-- <span>是否预售活动</span>
          <el-switch v-model="shetuanForm.pre" active-color="#13ce66" inactive-color="#ff4949">
          </el-switch> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogShetuanVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitShetuanForm('shetuanForm')" :loading="btnLoading">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as API_Promotion from '@/api/promotion'
import { parseTime } from '@/utils/index.js'
export default {
  name: 'shetuanList',
  data() {
    return {
      /** 列表loading状态 */
      loading: false,
      /** 确定按钮loading状态 */
      btnLoading: false,
      /** 列表参数 */
      params: {
        page_no: 1,
        page_size: 50
      },
      /** 列表数据 */
      tableData: '',
      dialogShetuanVisible: false,
      dialogPushVisible: false,
      //判断dialog的标题
      titleMap: {
        'new': '新增团购活动',
        'edit': '编辑团购活动',
        'copy': '复制团购活动',
        'push': '推送活动提醒'
      },
      //当前选中的标题
      titleType: 'new',
      //选中的参团状态
      slectVal: '',
      // 状态
      shetuanStatus: '',
      //表格勾选的行数
      tableRows: [],
      yusou: false,
      /** 活动推送 表单 */
      pushForm: {
        activity_name: '',
        activity_content: '',
        activity_time: '',
        reminder: '',
        activity_id: ''
      },
      /** 添加团购 表单 */
      shetuanForm: {
        address: '',
        city: '',
        city_id: '',
        county: '',
        county_id: '',
        create_time: '',
        description: '',
        end_time: '',
        join_stop_time: '',
        pick_time: '',
        planOnTime: '',
        pre: false,
        province: '',
        province_id: '',
        seller_id: '',
        seller_name: '',
        shetuan_id: '',
        shetuan_name: '',
        shetuan_info: '',
        shetan_remind: '',
        shetuan_no: '',
        start_time: '',
        status: '',
        time_range: [],
        page_popup: 0
        // region: ''
      },
      /** 添加团购 表单规则 */
      pushRules: {
        activity_name: [
          { required: true, message: '请输入活动名称', trigger: 'blur' }
        ],
        activity_content: [
          { required: true, message: '请输入活动内容', trigger: 'blur' }
        ],
        activity_time: [
          { required: true, message: '请选择活动时间', trigger: 'change' }
        ],
        reminder: [
          { required: true, message: '请输入提示内容', trigger: 'blur' }
        ]
      },
      /** 添加团购 表单规则 */
      shetuanRules: {
        shetuan_name: [
          {
            required: true, message: '请输入活动名称', trigger: 'change'
          }
        ],
        act_name: [this.MixinRequired('请输入活动名称！')],
        time_range: [
          this.MixinRequired('请选择活动时间段！')
          // { validator: (rule, value, callback) => {
          //   const { join_stop_time } = this.shetuanForm
          //   if (!join_stop_time) {
          //     callback();
          //   } else {
          //     if (value){
          //       value[0] > join_stop_time ? callback() : callback(new Error('活动开始时间必须大于报名截止时间！'))
          //     } else {
          //       callback();
          //     }
          //   }
          // } }
        ],
        join_stop_time: [
          this.MixinRequired('请选择截止报名时间！')
          // { validator: (rule, value, callback) => {
          //   const { time_range } = this.shetuanForm
          //   if (!time_range) {
          //     callback()
          //   } else {
          //     value < time_range[0] ? callback() : callback(new Error('报名截止时间必须小于活动开始时间！'))
          //   }
          // } }
        ],
        pick_time: [
          { type: 'date', required: true, message: '请选择时间', trigger: 'blur' }
        ]
        // region: [
        //   { required: true, message: '请选择所在地区', trigger: 'blur' }
        // ]
      },
      areas: []
    }
  },
  computed: {
    mixintime() {
      let _this = this;
      let date = new Date();
      date = parseTime( Date.parse(date))
      date = date.replace(/-/g, '/')
      let oDate = new Date(date)
      let stamp = oDate.getTime()
      let minute = oDate.getMinutes()
      let last = minute % 60
      if (last) {         
        stamp += (60 - last) * 60 * 1000
      }
      oDate = new Date(stamp)
      let t = {
        year: _this.pad_2_0(oDate.getFullYear()),
        month: _this.pad_2_0(oDate.getMonth() + 1),
        day: _this.pad_2_0(oDate.getDate()),
        hour: _this.pad_2_0(oDate.getHours()),
        minute: _this.pad_2_0(oDate.getMinutes()),
        second: _this.pad_2_0(oDate.getSeconds())
      }
      if (t.second > 0) {
        t.second = '00'
      }
      let res =  t.hour + ':' + t.minute + ':' + t.second;
      return res;
    }
  },
  mounted() {
    this.GET_ShetuanList()
  },
  methods: {
    pad_2_0(num) {
      return num >= 10 ? num : '0' + num
    },
    /**
      * @date 2020/06/12
      * @author lxw
      * @description {表单重置}
    */
    resetForm(formName) {
      if (this.$refs[formName] !== undefined) {
        this.$refs[formName].resetFields();
      }
    },

    /** 分页大小发生改变 */
    handlePageSizeChange(size) {
      this.params.page_size = size;
      this.GET_ShetuanList();
    },

    /** 分页页数发生改变 */
    handlePageCurrentChange(page) {
      this.params.page_no = page
      this.GET_ShetuanList()
    },

    /**
      * @date 2020/06/16
      * @author lxw
      * @description {多选事件}
    */
    selectedBox(selection){
      this.tableRows = selection;
    },

    /**
      * @date 2020/06/10
      * @author lxw
      * @description {复制活动}
    */
    copyActivityFn() {
      if (this.tableRows.length > 1){
        this.$message.success('只能选择一行复制');
        return;
      } else if (this.tableRows.length === 0){
        this.$message.success('请选择一行团购活动');
        return;
      } else {
        this.resetForm('shetuanForm');
        this.dialogShetuanVisible = true;
        this.titleType = 'copy';
        let _obj = this.MixinClone(this.tableRows[0]);
        _obj.join_stop_time = '';
        _obj.pick_time = '';
        _obj.shetuan_name = _obj.shetuan_name + '-副本';
        this.shetuanForm = _obj;
      }
    },

    /**
      * @date 2020/11/09
      * @author luocheng
      * @description {推送提醒}
    */
    pushNoticeFn() {
      if (this.tableRows.length > 1){
        this.$message.warning('只能选择一个活动推送');
        return;
      } else if (this.tableRows.length === 0){
        this.$message.warning('请选择一个行团购活动');
        return;
      } else {
        this.resetForm('pushForm');
        this.dialogPushVisible = true;
        this.titleType = 'push';
      }
    },

    /** 添加/编辑团购活动 */
    handleAddShetuan(_row) {
      this.resetForm('shetuanForm');
      this.titleType = _row ? 'edit' : 'new';
      this.dialogShetuanVisible = true;
      if (_row) {
        let _obj = this.MixinClone(_row);
        _obj.time_range = [parseInt(_obj.start_time) * 1000, parseInt(_obj.end_time) * 1000];
        _obj.planOnTime = parseInt(_obj.plan_on_time) * 1000;
        _obj.pick_time = parseInt(_obj.pick_time) * 1000;
        _obj.join_stop_time = parseInt(_obj.join_stop_time) * 1000;
        this.shetuanForm = _obj;
      }
    },

    /**
      * @date 2020/11/10
      * @author luocheng
      * @description {推送活动}
    */
    submitpushForm(formName) {
      this.btnLoading = true;
      const _time_range = this.pushForm.activity_time
      this.$refs[formName].validate((valid) => {
        const params = this.MixinClone(this.pushForm)
        if (valid) {
          params.activity_id = this.tableRows[0].shetuan_id
          params.activity_time = Date.parse(params.activity_time);
          API_Promotion.pushShetuanActive(params).then(response => {
            this.dialogPushVisible = false;
            this.$message.success('推送成功！');
            this.btnLoading = false;
            this.resetForm(formName);
          }).catch ((response) => {
            this.btnLoading = false;
          });
        }
      })
    },

    /** 提交添加/编辑/复制 团购表单 */
    submitShetuanForm(formName) {
      this.btnLoading = true;
      const _time_range = this.shetuanForm.time_range
      this.$refs[formName].validate((valid) => {
        const params = this.MixinClone(this.shetuanForm)
        if (valid) {
          const { shetuan_id } = params
          if (params.pre===true) {
            params.pre = 1;
          } else {
            params.pre = 0;
          }
          // params.join_stop_time /= 1000
          params.start_time = params.time_range[0] = _time_range[0] / 1000;
          params.end_time = params.time_range[1] = _time_range[1] / 1000;
          params.join_stop_time = params.join_stop_time / 1000;
          params.pick_time = params.pick_time / 1000;
          // params.plan_on_time = params.planOnTime = params.planOnTime / 1000;
          if (this.titleType === 'copy'){
            API_Promotion.copyActivity(params).then(response => {
              this.dialogShetuanVisible = false;
              this.GET_ShetuanList();
              this.$message.success('复制成功！');
              this.resetForm(formName);
            });
          } else {
            if (shetuan_id || shetuan_id === 0) {
              API_Promotion.editShetuanActive(params).then(response => {
                this.dialogShetuanVisible = false;
                this.GET_ShetuanList();
                this.$message.success('修改成功！');
                this.resetForm(formName);
              });
            } else {
              API_Promotion.addShetuanActive(params).then(response => {
                this.dialogShetuanVisible = false;
                this.GET_ShetuanList();
                this.$message.success('添加成功！');
                this.btnLoading = false;
                this.resetForm(formName);
                // this.areas = [];
              }).catch ((response) => {
                this.btnLoading = false;
              });
            }
          }
        } else {
          this.$message.error('表单填写有误，请检查！');
          this.btnLoading = false;
          return false;
        }
      })
    },
    /** 活动列表 */
    GET_ShetuanList() {
      this.loading = true
      API_Promotion.getShetuanActives(this.params).then(response => {
        this.loading = false;
        this.tableData = response;
      }).catch(() => { this.loading = false })
    },

    /**
      * @date 2020/06/08
      * @author lxw
      * @description {上线活动请求}
    */
    onlineHandle(index, id){
      this.$confirm('确认上线该活动, 是否继续?', '提示', { type: 'warning' }).then(() => {
        this.loading = true
        API_Promotion.postShetuanOnline(id).then(response => {
          this.tableData.data.splice(index, 1, response)
          this.$message.success('上线成功！')
          this.loading = false
        }).catch(() => { this.loading = false })
      })
    },

    /**
      * @date 2020/06/08
      * @author lxw
      * @description {活动下线请求}
    */
    offlineHandle(index, id){
      this.$confirm('确认下线该活动, 是否继续?', '提示', { type: 'warning' }).then(() => {
        this.loading = true
        API_Promotion.postShetuanOffline(id).then(response => {
          this.tableData.data.splice(index, 1, response)
          this.$message.success('下线成功！')
          this.loading = false
        }).catch(() => { this.loading = false })
      })
    },

    /**
      * @date 2020/06/08
      * @author lxw
      * @description {删除活动请求}
    */
    handleDeleteShetuan(id){
      this.$confirm('确认删除该活动, 是否继续?', '提示', { type: 'warning' }).then(() => {
        this.loading = true
        API_Promotion.delShetuanActivity(id).then(response => {
          this.$message.success('删除成功！');
          this.loading = false;
          this.GET_ShetuanList();
        }).catch(() => { this.loading = false })
      })
    },

    /**
      * @date 2020/06/09
      * @author lxw
      * @description {修改社团活动}
    */
    amendSheTuan(id){
      this.dialogShetuan = true;
    },

    /**
      * @date 2020/06/08
      * @author yg
      * @description {跳转到商品列表页}
    */
    manageGoods(id){
      this.$router.push({ name: 'shetuanGoodsList', params: { shetuan_id: id }})
    }
  }
}
</script>
<style type='text/scss' lang='scss' scoped>
.ac_area {
  width: 398px;
}
.t_scroll {
  overflow: auto;
}
.toolbar-btns {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}
.self_flex {
  display: flex;
}
.input-with-select {
  margin-right: 1rem;
}
.el-select {
  width: 100px;
}
.input-with-select .el-input-group__prepend {
  background-color: #fff;
}
.preview {
  width: 100%;
  height: 100%;
}
.el-input {
  width: 100%;
}
.areaItem{
  display: flex;
  flex-flow: row wrap;
  justify-content: start;
  .detailAddr{
    width: 400px;
    margin-left: 10px;
  }
}
.el-input__inner {
  width: 100%;
}
</style>
